package server

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/user/go-capcut/internal/config"
	"github.com/user/go-capcut/internal/downloader"
	"github.com/user/go-capcut/internal/draft"
	"github.com/user/go-capcut/internal/handler"
)

// Server HTTP服务器
type Server struct {
	Engine     *gin.Engine
	Config     *config.Config
	Handler    *handler.Handler
	HttpServer *http.Server
}

// NewServer 创建新的服务器
func NewServer(cfg *config.Config) *Server {
	// 创建Gin引擎
	gin.SetMode(gin.ReleaseMode)
	engine := gin.New()
	engine.Use(gin.Logger(), gin.Recovery())

	// 配置CORS
	engine.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	// 创建缓存
	cache := draft.NewLRUCache(100)

	// 创建下载器
	downloader := downloader.NewFileDownloader()

	// 创建处理器
	h := handler.NewHandler(cfg, cache, downloader)

	// 创建HTTP服务器
	httpServer := &http.Server{
		Addr:    fmt.Sprintf(":%d", cfg.Port),
		Handler: engine,
	}

	return &Server{
		Engine:     engine,
		Config:     cfg,
		Handler:    h,
		HttpServer: httpServer,
	}
}

// RegisterRoutes 注册路由
func (s *Server) RegisterRoutes() {
	// 健康检查
	s.Engine.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	// API路由
	s.Engine.GET("/create_draft", s.Handler.CreateDraft)
	s.Engine.GET("/query_draft_status", s.Handler.QueryDraftStatus)
	s.Engine.GET("/add_video", s.Handler.AddVideo)
	s.Engine.GET("/add_audio", s.Handler.AddAudio)
	s.Engine.GET("/add_text", s.Handler.AddText)
	s.Engine.GET("/add_image", s.Handler.AddImage)
	s.Engine.GET("/add_effect", s.Handler.AddEffect)
	s.Engine.GET("/save_draft", s.Handler.SaveDraft)

	// 静态文件服务
	staticHandler := NewStaticHandler("./web")
	staticHandler.RegisterRoutes(s.Engine)
}

// Start 启动服务器
func (s *Server) Start() error {
	// 注册路由
	s.RegisterRoutes()

	// 启动服务器
	log.Printf("Server starting on port %d...", s.Config.Port)
	return s.HttpServer.ListenAndServe()
}

// Stop 停止服务器
func (s *Server) Stop(ctx context.Context) error {
	log.Println("Server shutting down...")
	return s.HttpServer.Shutdown(ctx)
}
